package com.minelx.landisk.filesystem.core;

import com.minelx.landisk.filesystem.core.init.OpenPolicy;
import com.minelx.landisk.filesystem.core.provider.FS;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import static com.minelx.landisk.filesystem.core.init.OpenPolicy.*;

public class TempPath implements AutoCloseable {

	private static final Directory TEMP_FILES_DIRECTORY = FS.workingDir()
			.child().dir("temp_files", CREATE_IF_NOT_EXISTED);

	private final Path path;

	private TempPath(Path path) {
		this.path = path;
	}

	public File file() {
		return file(CREATE_IF_NOT_EXISTED);
	}

	public Directory dir() {
		return dir(CREATE_IF_NOT_EXISTED);
	}

	public File file(OpenPolicy openPolicy) {
		return File.create(path, openPolicy);
	}

	public Directory dir(OpenPolicy openPolicy) {
		return Directory.create(path, openPolicy);
	}

	@Override
	public void close() {
		path.deleteIfExists();
	}

	public static TempPath of(String fileName) {
		Path path = TEMP_FILES_DIRECTORY.child().path(fileName);
		return new TempPath(path);
	}

	public static TempPath random(String content) {
		try {
			TempPath result = random();
			result.file().write(content, StandardCharsets.UTF_8);
			return result;
		} catch (IOException e) {
			throw new RuntimeException("error while writing content to random file.", e);
		}
	}

	public static TempPath random() {
		return TempPath.of(UUID.randomUUID().toString());
	}
}